package com.wolfalpha.utron.activity;

import android.app.ActivityManager;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.EMConnectionListener;
import com.easemob.EMEventListener;
import com.easemob.EMGroupChangeListener;
import com.easemob.EMNotifierEvent;
import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.EMLog;
import com.easemob.util.HanziToPinyin;
import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.base.BaseActivity;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.app.AppManager;
import com.wolfalpha.utron.bean.UserInfo;
import com.wolfalpha.utron.fragment.MainIdea;
import com.wolfalpha.utron.fragment.MainInformation;
import com.wolfalpha.utron.fragment.MainPartner;
import com.wolfalpha.utron.fragment.MainProject;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.ImageUtils;
import com.wolfalpha.utron.utils.StringUtils;
import com.wolfalpha.utron.view.AlertDialog;
import com.wolfalpha.utron.view.CallsAlertDialog;
import com.wolfalpha.utron.view.CircleImageView;
import com.wolfalpha.utron.view.DirsAlertDialog;
import com.wolfalpha.utron.view.LevelAlertDialog;
import com.wolfalpha.utron.view.MIPPopWindow;
import com.wolfalpha.utron.view.MPartnerPopWindow;
import com.wolfalpha.utron.view.SlidingMenu;
import com.wolfalpha.utron.view.SortAlertDialog;
import com.wolfalpha.utron.view.TimeinAlertDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import easemob.applib.controller.HXSDKHelper;
import easemob.chatuidemo.Constant;
import easemob.chatuidemo.DemoHXSDKHelper;
import easemob.chatuidemo.activity.AddContactActivity;
import easemob.chatuidemo.activity.ChatActivity;
import easemob.chatuidemo.activity.NewFriendsMsgActivity;
import easemob.chatuidemo.db.InviteMessgeDao;
import easemob.chatuidemo.db.UserDao;
import easemob.chatuidemo.domain.InviteMessage;
import easemob.chatuidemo.domain.User;
import easemob.chatuidemo.utils.UserUtils;

/**
 * 主界面
 */
public class MainActivity extends BaseActivity implements View.OnClickListener, EMEventListener {

    private RelativeLayout flContainer;        //中间内容区

    private LinearLayout lyCollection;      //我的收藏
    private LinearLayout lyAttention;       //我的关注
    private LinearLayout lyActivity;        //Utron活动
    private LinearLayout lyNotice;          //通知
    private LinearLayout lyRequire;         //需求穿越
    private LinearLayout lySetting;         //设置按钮

    private LinearLayout llBottomIdea;         //创意菜单
    private LinearLayout llBottomProject;      //项目菜单
    private LinearLayout llBottomPartner;      //合伙人菜单
    private LinearLayout llBottomInformation;  //资讯菜单

    private ImageView ivBottomIdea;            //创意菜单图标
    private ImageView ivBottomProject;         //项目菜单图标
    private ImageView ivBottomPartner;         //合伙人菜单图标
    private ImageView ivBottomInformation;     //资讯菜单图标

    private TextView tvBottomIdea;             //创意菜单文字
    private TextView tvBottomProject;          //项目菜单文字
    private TextView tvBottomPartner;          //合伙人菜单文字
    private TextView tvBottomInformation;      //资讯菜单文字


    private ImageView ivHead;               //用户头像

    private ImageView ivCollection;         //收藏图标
    private ImageView ivAttention;          //关注图标
    private ImageView ivActivity;           //活动图标
    private ImageView ivRelation;           //与我相关图标
    private ImageView ivRequire;            //需求穿越图标
    private ImageView ivSetting;            //设置图标


    private TextView tvNickName;            //用户昵称文字
    private TextView tvSign;                //用户签名文字
    private TextView tvCollection;          //收藏文字
    private TextView tvAttention;           //关注文字
    private TextView tvActivity;            //活动文字
    private TextView tvRelation;            //与我相关文字
    private TextView tvRequire;             //需求穿越文字
    private TextView tvSetting;             //设置文字

    private TextView tvShadow;              //黑色背景

    private CircleImageView civHead;        //左侧头像
    private TextView titleBar;              //中间的文字
    private ImageView ivOper;               //右侧的操作

    private UserInfo userInfo;              //个人信息

    private LinearLayout llPartnerBar;      //伙伴选择栏
    private CheckBox cbMsg;                 //伙伴消息
    private CheckBox cbPartner;             //伙伴合伙人
    private CheckBox cbFriends;             //伙伴好友


    private int bIndex = 1;                  //当前菜单1：创意；2：项目；3：合伙人；4：资讯

    private MainInformation mainInformation;        //资讯
    private MainProject mainProject;                //项目
    private MainIdea mainInIdea;                    //创意
    private MainPartner mainPartner;                //合伙人

    private SlidingMenu slidingMenu;            //侧滑

    public static MainActivity mainActivity = null;

    private boolean isLogined = false;          //是否登录

    /**
     * 对外的实例
     *
     * @return
     */
    public static MainActivity getInstance() {
        if (mainActivity != null) {
            return mainActivity;
        }
        return null;
    }

    /**
     * 对外的刷新
     */
    public void refreshGroup() {
        mainPartner.groupRefresh();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AppManager.getAppManager().addActivity(this);

        if (mainActivity == null) mainActivity = this;

        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        if (savedInstanceState == null) {
            mainInformation = new MainInformation();
            mainProject = new MainProject();
            mainInIdea = new MainIdea();
            mainPartner = new MainPartner();

            ft.add(R.id.rl_main_middle_container, mainInformation, "m_info");
            ft.add(R.id.rl_main_middle_container, mainProject, "m_pro");
            ft.add(R.id.rl_main_middle_container, mainInIdea, "m_idea");
            ft.add(R.id.rl_main_middle_container, mainPartner, "m_par");

            ft.hide(mainInformation);
            ft.hide(mainProject);
            ft.hide(mainPartner);

            ft.commit();
        } else {
            mainInIdea = (MainIdea) fm.findFragmentByTag("m_idea");
            mainProject = (MainProject) fm.findFragmentByTag("m_pro");
            mainPartner = (MainPartner) fm.findFragmentByTag("m_par");
            mainInformation = (MainInformation) fm.findFragmentByTag("m_info");
        }

        initView();
        initListeners();
        initHx();

        /**
         * 注册头像变化接收器
         */

        try {
            IntentFilter headFilter = new IntentFilter();
            headFilter.addAction(UserCenterActivity.HEAD_CHANGED);
            registerReceiver(avtarChangedReciver, headFilter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
        outState.putInt("position", bIndex);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        bIndex = savedInstanceState.getInt("position");
        selectIndex(bIndex);
        super.onRestoreInstanceState(savedInstanceState);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        civHead = (CircleImageView) findViewById(R.id.header_iv_user_head);
        slidingMenu = (SlidingMenu) findViewById(R.id.sld_menu);

        titleBar = (TextView) findViewById(R.id.header_tv_title);
        titleBar.setText("灵感");
        ivOper = (ImageView) findViewById(R.id.header_iv_right);

        flContainer = (RelativeLayout) findViewById(R.id.rl_main_middle_container);

        ivBottomIdea = (ImageView) findViewById(R.id.iv_main_bottom_idea);
        ivBottomProject = (ImageView) findViewById(R.id.iv_main_bottom_project);
        ivBottomPartner = (ImageView) findViewById(R.id.iv_main_bottom_partner);
        ivBottomInformation = (ImageView) findViewById(R.id.iv_main_bottom_information);

        tvBottomIdea = (TextView) findViewById(R.id.tv_main_bottom_idea);
        tvBottomProject = (TextView) findViewById(R.id.tv_main_bottom_project);
        tvBottomPartner = (TextView) findViewById(R.id.tv_main_bottom_partner);
        tvBottomInformation = (TextView) findViewById(R.id.tv_main_bottom_information);

        tvNickName = (TextView) findViewById(R.id.tv_main_menu_nickname);
        tvSign = (TextView) findViewById(R.id.tv_main_menu_sign);
        tvCollection = (TextView) findViewById(R.id.tv_main_menu_collection);
        tvAttention = (TextView) findViewById(R.id.tv_main_menu_attention);
        tvActivity = (TextView) findViewById(R.id.tv_main_menu_activity);
        tvRelation = (TextView) findViewById(R.id.tv_main_menu_relation);
        tvRequire = (TextView) findViewById(R.id.tv_main_menu_require);
        tvSetting = (TextView) findViewById(R.id.tv_main_menu_setting);

        ivHead = (ImageView) findViewById(R.id.iv_main_menu_user_head);
        ivCollection = (ImageView) findViewById(R.id.iv_main_menu_collection);
        ivAttention = (ImageView) findViewById(R.id.iv_main_menu_attention);
        ivActivity = (ImageView) findViewById(R.id.iv_main_menu_activity);
        ivRelation = (ImageView) findViewById(R.id.iv_main_menu_relation);
        ivRequire = (ImageView) findViewById(R.id.iv_main_menu_require);
        ivSetting = (ImageView) findViewById(R.id.iv_main_menu_setting);

        lyCollection = (LinearLayout) findViewById(R.id.ly_main_menu_collection);
        lyAttention = (LinearLayout) findViewById(R.id.ly_main_menu_attention);
        lyActivity = (LinearLayout) findViewById(R.id.ly_main_menu_activity);
        lyNotice = (LinearLayout) findViewById(R.id.ly_main_menu_relation);
        lyRequire = (LinearLayout) findViewById(R.id.ly_main_menu_require);
        lySetting = (LinearLayout) findViewById(R.id.ly_main_menu_setting);

        llBottomPartner = (LinearLayout) findViewById(R.id.ll_main_bottom_partner);
        llBottomProject = (LinearLayout) findViewById(R.id.ll_main_bottom_project);
        llBottomIdea = (LinearLayout) findViewById(R.id.ll_main_bottom_idea);
        llBottomInformation = (LinearLayout) findViewById(R.id.ll_main_bottom_information);

        llPartnerBar = (LinearLayout) findViewById(R.id.ll_main_partner_bars);
        cbMsg = (CheckBox) findViewById(R.id.cb_main_partner_message);
        cbPartner = (CheckBox) findViewById(R.id.cb_main_partner_partner);
        cbFriends = (CheckBox) findViewById(R.id.cb_main_partner_friends);

        tvShadow = (TextView) findViewById(R.id.tv_shadow_popwindow);

        selectIndex(bIndex);
    }


    /**
     * 底部按钮
     *
     * @param view
     */
    public void doChoose(View view) {
        if (view == llBottomIdea) {
            selectIndex(1);
            bIndex = 1;
        } else if (view == llBottomProject) {
            selectIndex(2);
            bIndex = 2;
        } else if (view == llBottomPartner) {
            selectIndex(3);
            bIndex = 3;
        } else if (view == llBottomInformation) {
            selectIndex(4);
            bIndex = 4;
        }
    }

    /**
     * 菜单底部变化
     *
     * @param i
     */
    private void selectIndex(int i) {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        if (i == 1) {
            //选择了创意菜单
            ivBottomIdea.setImageResource(R.mipmap.main_bottom_idea_selected);
            ivBottomInformation.setImageResource(R.mipmap.main_bottom_information_normal);
            ivBottomPartner.setImageResource(R.mipmap.main_bottom_partner_normal);
            ivBottomProject.setImageResource(R.mipmap.main_bottom_project_normal);

            tvBottomIdea.setTextColor(getResources().getColor(R.color.main_bottom_text_selected));
            tvBottomProject.setTextColor(getResources().getColor(R.color.main_bottom_text_normal));
            tvBottomPartner.setTextColor(getResources().getColor(R.color.main_bottom_text_normal));
            tvBottomInformation.setTextColor(getResources().getColor(R.color.main_bottom_text_normal));

            if (mainInIdea.isHidden()) {
                ft.show(mainInIdea);
            }
            if (mainProject.isVisible()) {
                ft.hide(mainProject);
            }
            if (mainPartner.isVisible()) {
                ft.hide(mainPartner);
            }
            if (mainInformation.isVisible()) {
                ft.hide(mainInformation);
            }
            titleBar.setText("灵感");
            ivOper.setVisibility(View.VISIBLE);
            ivOper.setImageResource(R.mipmap.app_operation_more);
            llPartnerBar.setVisibility(View.GONE);
            titleBar.setVisibility(View.VISIBLE);
            bIndex = 1;
        } else if (i == 2) {
            //选择了项目菜单
            ivBottomIdea.setImageResource(R.mipmap.main_bottom_idea_normal);
            ivBottomInformation.setImageResource(R.mipmap.main_bottom_information_normal);
            ivBottomPartner.setImageResource(R.mipmap.main_bottom_partner_normal);
            ivBottomProject.setImageResource(R.mipmap.main_bottom_project_selected);

            tvBottomIdea.setTextColor(getResources().getColor(R.color.main_bottom_text_normal));
            tvBottomProject.setTextColor(getResources().getColor(R.color.main_bottom_text_selected));
            tvBottomPartner.setTextColor(getResources().getColor(R.color.main_bottom_text_normal));
            tvBottomInformation.setTextColor(getResources().getColor(R.color.main_bottom_text_normal));

            if (mainInIdea.isVisible()) {
                ft.hide(mainInIdea);
            }
            if (mainProject.isHidden()) {
                ft.show(mainProject);
            }
            if (mainPartner.isVisible()) {
                ft.hide(mainPartner);
            }
            if (mainInformation.isVisible()) {
                ft.hide(mainInformation);
            }
            titleBar.setText("项目");
            ivOper.setVisibility(View.VISIBLE);
            ivOper.setImageResource(R.mipmap.app_operation_more);
            llPartnerBar.setVisibility(View.GONE);
            titleBar.setVisibility(View.VISIBLE);
            bIndex = 2;
        } else if (i == 3) {
            //选择了合伙人菜单
            ivBottomIdea.setImageResource(R.mipmap.main_bottom_idea_normal);
            ivBottomInformation.setImageResource(R.mipmap.main_bottom_information_normal);
            ivBottomPartner.setImageResource(R.mipmap.main_bottom_partner_selected);
            ivBottomProject.setImageResource(R.mipmap.main_bottom_project_normal);

            tvBottomIdea.setTextColor(getResources().getColor(R.color.main_bottom_text_normal));
            tvBottomProject.setTextColor(getResources().getColor(R.color.main_bottom_text_normal));
            tvBottomPartner.setTextColor(getResources().getColor(R.color.main_bottom_text_selected));
            tvBottomInformation.setTextColor(getResources().getColor(R.color.main_bottom_text_normal));

            if (mainInIdea.isVisible()) {
                ft.hide(mainInIdea);
            }
            if (mainProject.isVisible()) {
                ft.hide(mainProject);
            }
            if (mainPartner.isHidden()) {
                ft.show(mainPartner);
            }
            if (mainInformation.isVisible()) {
                ft.hide(mainInformation);
            }

            titleBar.setVisibility(View.GONE);
            checkPartnerBar(pindex);
//            ivOper.setImageResource(R.mipmap.main_partner_choose);
            llPartnerBar.setVisibility(View.VISIBLE);
            bIndex = 3;

        } else if (i == 4) {
            //选择了资讯菜单
            ivBottomIdea.setImageResource(R.mipmap.main_bottom_idea_normal);
            ivBottomInformation.setImageResource(R.mipmap.main_bottom_information_selected);
            ivBottomPartner.setImageResource(R.mipmap.main_bottom_partner_normal);
            ivBottomProject.setImageResource(R.mipmap.main_bottom_project_normal);

            tvBottomIdea.setTextColor(getResources().getColor(R.color.main_bottom_text_normal));
            tvBottomProject.setTextColor(getResources().getColor(R.color.main_bottom_text_normal));
            tvBottomPartner.setTextColor(getResources().getColor(R.color.main_bottom_text_normal));
            tvBottomInformation.setTextColor(getResources().getColor(R.color.main_bottom_text_selected));

            if (mainInIdea.isVisible()) {
                ft.hide(mainInIdea);
            }
            if (mainProject.isVisible()) {
                ft.hide(mainProject);
            }
            if (mainPartner.isVisible()) {
                ft.hide(mainPartner);
            }
            if (mainInformation.isHidden()) {
                ft.show(mainInformation);
            }

            titleBar.setText("资讯");
            ivOper.setVisibility(View.INVISIBLE);
            llPartnerBar.setVisibility(View.INVISIBLE);
            titleBar.setVisibility(View.VISIBLE);
            bIndex = 4;
        }

        ft.commit();
    }

    private int pindex = 0;

    /**
     * 选择伙伴状态栏
     */
    private void checkPartnerBar(int index1) {
        isAddFriend = false;
        if (index1 == 0) {
            //消息
            cbMsg.setChecked(true);
            cbPartner.setChecked(false);
            cbFriends.setChecked(false);
            ivOper.setVisibility(View.INVISIBLE);
            mainPartner.doSwitch(0);
            pindex = 0;
        }
        if (index1 == 1) {
            //合伙人列表
            cbMsg.setChecked(false);
            cbPartner.setChecked(true);
            cbFriends.setChecked(false);
            ivOper.setVisibility(View.VISIBLE);
            ivOper.setImageResource(R.mipmap.main_partner_choose);
            mainPartner.doSwitch(1);
            pindex = 1;
        }
        if (index1 == 2) {
            //好友
            if (!checkLogin()) {
                checkPartnerBar(0);
                return;
            }
            cbMsg.setChecked(false);
            cbPartner.setChecked(false);
            cbFriends.setChecked(true);
            ivOper.setVisibility(View.VISIBLE);
            ivOper.setImageResource(R.mipmap.partner_partner_add_new);
            mainPartner.doSwitch(2);
            isAddFriend = true;
            pindex = 2;
        }


    }

    private boolean isAddFriend = false;

    /**
     * 设置内容
     */
    public void initText(UserInfo userInfo) {
        if (userInfo != null) {
            tvNickName.setText(userInfo.getNickname() != null ? userInfo.getNickname() : "");
            tvSign.setText(userInfo.getUtron_sign());
            initUserHead();
        } else {
            tvNickName.setText("请登录");
            tvSign.setText("...");
        }

    }

    private void initUserHead() {
        if (ImageUtils.getBitmap(MainActivity.this, "head_pic.jpg") != null) {
            ivHead.setImageBitmap(ImageUtils.getBitmap(MainActivity.this, "head_pic.jpg"));
            civHead.setImageBitmap(ImageUtils.getBitmap(MainActivity.this, "head_pic.jpg"));
        }
    }

    private boolean hasLogined = false;

    @Override
    public void onResume() {
        super.onResume();

        if (hasLogined) {
            return;
        }

        isLogined = AppContext.getInstance().getIsLogined();

        try {
            if (isLogined) {
                userInfo = AppContext.getInstance().getUserInfo();
                hasLogined = true;
                if (userInfo != null)
                    initText(userInfo);
            } else {
//                initText(null);
                AlertDialog dialog = new AlertDialog(MainActivity.this);
                dialog.setMessage("您还未登录，请先登录后使用!");
                dialog.setTitle("抱歉");
                dialog.setOnlyPositive();
                dialog.setPositiveButton("登录", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        UIHelper.showActivityAndFinish(MainActivity.this, LoginActivity.class);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (isLogined) {

            updateUnreadLabel();
            updateUnreadAddressLable();
            EMChatManager.getInstance().activityResumed();

            // unregister this event listener when this activity enters the
            // background
            DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper.getInstance();
            sdkHelper.pushActivity(this);

            // register the event listener when enter the foreground
            EMChatManager.getInstance().registerEventListener(this,
                    new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage, EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventConversationListChanged});
        }

    }

    /**
     * 初始化监听器
     */
    private void initListeners() {
        lyCollection.setOnClickListener(this);
        lyAttention.setOnClickListener(this);
        lyActivity.setOnClickListener(this);
        lyNotice.setOnClickListener(this);
        lyRequire.setOnClickListener(this);
        lySetting.setOnClickListener(this);
        ivHead.setOnClickListener(this);
        tvNickName.setOnClickListener(this);
        tvSign.setOnClickListener(this);

        ivOper.setOnClickListener(this);
        titleBar.setOnClickListener(this);
        civHead.setOnClickListener(this);

        cbFriends.setOnClickListener(this);
        cbPartner.setOnClickListener(this);
        cbMsg.setOnClickListener(this);
    }

    /**
     * 判断登录
     */
    public boolean checkLogin() {
        if (!isLogined) {
            UIHelper.showNotLogined(MainActivity.this);
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cb_main_partner_friends:
                checkPartnerBar(2);
                break;
            case R.id.cb_main_partner_message:
                checkPartnerBar(0);
                break;
            case R.id.cb_main_partner_partner:
                checkPartnerBar(1);
                break;
            case R.id.header_iv_user_head:
                slidingMenu.toggle();
                break;
            case R.id.header_tv_title:
//                UIHelper.ToastMessage(MainActivity.this, "标题");
                break;
            case R.id.header_iv_right:
                if (bIndex == 2) {
                    showProjectMenu();
                }
                if (bIndex == 1) {

                    /**
                     * bugly 测试
                     */
//                    if (AppContext.getInstance().getDebug()) CrashReport.testJavaCrash();

                    showIdeaMenu();
                }
                if (bIndex == 3) {
                    //伙伴
                    if (isAddFriend) {
                        //添加新的好友
                        if (mainPartner.getContactIndex() == 2) {
                            //群
                            Bundle bundle = new Bundle();
                            bundle.putString("qun", "yes");
                            UIHelper.showActivity(MainActivity.this, AddContactActivity.class, bundle);
                        } else {
                            UIHelper.showActivity(MainActivity.this, AddContactActivity.class);
                        }
                    } else {
                        showPartnerMenu();
                    }
                }
                break;
        }


        switch (v.getId()) {
            case R.id.tv_main_menu_nickname:
            case R.id.tv_main_menu_sign:
            case R.id.iv_main_menu_user_head:
                //进入个人信息
                if (!checkLogin()) break;
                UIHelper.showActivity(MainActivity.this, UserCenterActivity.class);
                break;
            case R.id.ly_main_menu_collection:
                //进入个人收藏界面
                if (!checkLogin()) break;
                UIHelper.showActivity(MainActivity.this, MyCollectionActivity.class);
                break;
            case R.id.ly_main_menu_attention:
                //进入个人关注面
                if (!checkLogin()) break;
                UIHelper.showActivity(MainActivity.this, MyAttentionActivity.class);
                break;
            case R.id.ly_main_menu_activity:
                //进入Utron活动界面
                UIHelper.showActivity(MainActivity.this, UtronActivityActivity.class);
                break;
            case R.id.ly_main_menu_relation:
                //进入与我相关界面
                if (!checkLogin()) break;
                UIHelper.showActivity(MainActivity.this, NewFriendsMsgActivity.class);
                break;
            case R.id.ly_main_menu_require:
                //进入需求穿越界面
                if (!checkLogin()) break;
                UIHelper.showActivity(MainActivity.this, RequirementActivity.class);
                break;
            case R.id.ly_main_menu_setting:
                //进入设置界面
                UIHelper.showActivity(MainActivity.this, SettingActivity.class);
                break;
        }
    }

    /**
     * 显示灵感菜单
     */
    private void showIdeaMenu() {
        tvShadow.setVisibility(View.VISIBLE);
        final MIPPopWindow mPopWindow = new MIPPopWindow(MainActivity.this);
        mPopWindow.showPopupWindow(ivOper);
        mPopWindow.setOnButtonClickedListener(new MIPPopWindow.OnButtonClickedListener() {
            @Override
            public void click(int which) {
                if (which == 1) {
                    //发布灵感
                    UIHelper.showActivity(MainActivity.this, IdeaPublishActivity.class);
                }
                if (which == 2) {
                    //排序
                    final SortAlertDialog dialog = new SortAlertDialog(MainActivity.this);
                    dialog.setTitle("选择排序方式");
                    dialog.setOnButtonClickedListener(new SortAlertDialog.OnButtonClickedListener() {
                        @Override
                        public void click(int which) {
                            switch (which) {
                                case 1:
                                    //热度
                                    mainInIdea.sortByHot();
                                    break;
                                case 2:
                                    //时间
                                    mainInIdea.sortByTime();
                                    break;
                                case 3:
                                    //随机
                                    mainInIdea.sortByRand();
                                    break;
                            }
                            mPopWindow.dismiss();
                        }
                    });
                }
                if (which == 3) {
                    //筛选
                    final DirsAlertDialog dirsAlertDialog = new DirsAlertDialog(MainActivity.this, false);
                    final List<String> data = StringUtils.getDirsValues(MainActivity.this);
                    dirsAlertDialog.setData(data);
                    dirsAlertDialog.setTitle("选择感兴趣的标签");
                    dirsAlertDialog.setPositiveButton("确认", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            List<Integer> data = dirsAlertDialog.getResult();
                            if (data != null) {
                                List<Integer> datatemp = new ArrayList<Integer>();
                                for (int i : data) {
                                    datatemp.add(i + 1001);
                                }
                                mainInIdea.sortByDirs(datatemp);
                            }
                            dirsAlertDialog.dismiss();
                            mPopWindow.dismiss();

                        }
                    });
                    dirsAlertDialog.setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dirsAlertDialog.dismiss();
                        }
                    });
                }
            }
        });
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                tvShadow.setVisibility(View.GONE);
            }
        });
    }


    /**
     * 显示项目菜单
     */
    private void showProjectMenu() {
        tvShadow.setVisibility(View.VISIBLE);
        final MIPPopWindow mPopWindow = new MIPPopWindow(MainActivity.this);
        mPopWindow.showPopupWindow(ivOper);
        mPopWindow.setPublishText("发布项目");
        mPopWindow.setOnButtonClickedListener(new MIPPopWindow.OnButtonClickedListener() {
            @Override
            public void click(int which) {
                if (which == 1) {
                    //发布灵感
                    UIHelper.showActivity(MainActivity.this, ProjectPublishActivity.class);
                }
                if (which == 2) {
                    //排序
                    final SortAlertDialog dialog = new SortAlertDialog(MainActivity.this);
                    dialog.setTitle("选择排序方式");
                    dialog.setOnButtonClickedListener(new SortAlertDialog.OnButtonClickedListener() {
                        @Override
                        public void click(int which) {
                            switch (which) {
                                case 1:
                                    //热度
                                    mainProject.sortByHot();
                                    break;
                                case 2:
                                    //时间
                                    mainProject.sortByTime();
                                    break;
                                case 3:
                                    //随机
                                    mainProject.sortByRand();
                                    break;
                            }
                            mPopWindow.dismiss();
                        }
                    });
                }
                if (which == 3) {
                    //筛选
                    final DirsAlertDialog dirsAlertDialog = new DirsAlertDialog(MainActivity.this, false);
                    final List<String> data = StringUtils.getDirsValues(MainActivity.this);
                    dirsAlertDialog.setData(data);
                    dirsAlertDialog.setTitle("选择感兴趣的标签");
                    dirsAlertDialog.setPositiveButton("确认", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            List<Integer> data = dirsAlertDialog.getResult();
                            if (data != null) {
                                List<Integer> datatemp = new ArrayList<Integer>();
                                for (int i : data) {
                                    datatemp.add(i + 1001);
                                }
                                mainProject.sortByDirs(datatemp);
                            }
                            dirsAlertDialog.dismiss();
                            mPopWindow.dismiss();
                        }
                    });
                    dirsAlertDialog.setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dirsAlertDialog.dismiss();
                        }
                    });
                }
            }
        });
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                tvShadow.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 显示合伙人菜单
     */
    private void showPartnerMenu() {
        tvShadow.setVisibility(View.VISIBLE);
        final MPartnerPopWindow mPopWindow = new MPartnerPopWindow(MainActivity.this);
        mPopWindow.showPopupWindow(ivOper);
        mPopWindow.setOnButtonClickedListener(new MPartnerPopWindow.OnButtonClickedListener() {
            @Override
            public void click(int which) {
                if (which == 1) {
                    //角色选择
                    final CallsAlertDialog dialog = new CallsAlertDialog(MainActivity.this);
                    dialog.setTitle("选择合伙人角色");
                    dialog.setOnFinishedListener(new CallsAlertDialog.OnFinishedListener() {
                        @Override
                        public void finish(String input) {
                            mainPartner.sortByRole(input);
                            dialog.dismiss();
                            mPopWindow.dismiss();
                        }
                    });
                }
                if (which == 2) {
                    //等级
                    final LevelAlertDialog dialog = new LevelAlertDialog(MainActivity.this);
                    dialog.setTitle("选择合伙人等级");
                    dialog.setPositiveButton("确认", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mainPartner.sortByLevel(dialog.getResult());
                            dialog.dismiss();
                            mPopWindow.dismiss();
                        }
                    });
                    dialog.setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                }
                if (which == 3) {
                    //筛选
                    final TimeinAlertDialog dialog = new TimeinAlertDialog(MainActivity.this);
                    dialog.setTitle("选择投入时间范围");
                    dialog.setPositiveButton("确认", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mainPartner.sortByTime(dialog.getResult());
                            dialog.dismiss();
                            mPopWindow.dismiss();
                        }
                    });
                    dialog.setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                }
            }
        });
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                tvShadow.setVisibility(View.GONE);
            }
        });
    }

    private long lastTouchTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - lastTouchTime < 2000) {
                //两秒内点击两次退出
                int currentVersion = android.os.Build.VERSION.SDK_INT;
                if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
                    Intent startMain = new Intent(Intent.ACTION_MAIN);
                    startMain.addCategory(Intent.CATEGORY_HOME);
                    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(startMain);
                    System.exit(0);
                    onDestroy();
                } else {// android2.1
                    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                    am.restartPackage(getPackageName());
                    onDestroy();
                }
                return true;
            } else {
                //提示再点击一次退出
                UIHelper.ToastMessage(this, "再按一次退出");
                lastTouchTime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        EMChatManager.getInstance().unregisterEventListener(this);

        if (connectionListener != null) {
            EMChatManager.getInstance().removeConnectionListener(connectionListener);
        }

//        if (groupChangeListener != null) {
//            EMGroupManager.getInstance().removeGroupChangeListener(groupChangeListener);
//        }

        try {
            unregisterReceiver(avtarChangedReciver);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*好友相关监听**********************************************************************************************************************/

    private MyConnectionListener connectionListener = null;
    //    private MyGroupChangeListener groupChangeListener = null;
//    private InviteMessgeDao inviteMessgeDao;
    private UserDao userDao;


    @Override
    protected void onStop() {
        if (isLogined) {
            DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper.getInstance();
            sdkHelper.popActivity(this);
        }
        super.onStop();
    }

    /**
     * 初始化环信
     */
    private void initHx() {
//        inviteMessgeDao = new InviteMessgeDao(this);
        userDao = new UserDao(this);

//        ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getUserProfileManager().asyncGetCurrentUserInfo();

        // setContactListener监听联系人的变化等
//        EMContactManager.getInstance().setContactListener(new MyContactListener());
        // 注册一个监听连接状态的listener

        connectionListener = new MyConnectionListener();
        EMChatManager.getInstance().addConnectionListener(connectionListener);

//        groupChangeListener = new MyGroupChangeListener();
//         注册群聊相关的listener
//        EMGroupManager.getInstance().addGroupChangeListener(groupChangeListener);
    }


    /**
     * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
     *
     * @param username
     * @param user
     */
    private static void setUserHearder(String username, User user) {
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target.substring(0, 1)
                    .toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
    }

    /**
     * set head
     *
     * @param username
     * @return
     */
    User setUserHead(String username) {
        User user = new User();
        user.setUsername(username);
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target.substring(0, 1)
                    .toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
        return user;
    }

    /**
     * 监听事件
     */
    @Override
    public void onEvent(EMNotifierEvent event) {
        switch (event.getEvent()) {
            case EventNewMessage: // 普通消息
            {
                EMMessage message = (EMMessage) event.getData();

                try {
                    String userid = message.getFrom();
                    String avatar = message.getStringAttribute(ChatActivity.ATTR_AVATAR);
                    String nickname = message.getStringAttribute(ChatActivity.ATTR_NICK);
                    User user = UserUtils.getUserInfo(userid);
                    if (user != null) {
                        System.out.println(userid + " user null");
                        boolean change = false;
                        if (!user.getNick().equals(nickname)) {
                            user.setNick(nickname);
                            change = true;
                        }
                        if (!user.getAvatar().equals(avatar)) {
                            user.setAvatar(avatar);
                            change = true;
                        }
                        if (change) {
                            UserUtils.saveUserInfo(user);
                        }
                    } else {
                        user = new User(userid);
                        user.setAvatar(avatar);
                        user.setNick(nickname);
                        UserUtils.saveUserInfo(user);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(AppContext.getInstance(), "用户信息错误", Toast.LENGTH_SHORT).show();
                }

                // 提示新消息
                HXSDKHelper.getInstance().getNotifier().onNewMsg(message);
                refreshUI();

                break;
            }

            case EventOfflineMessage: {
                List<EMMessage> messages = (List<EMMessage>) event.getData();

                for (EMMessage message : messages) {
                    try {
                        String userid = message.getFrom();
                        String avatar = message.getStringAttribute(ChatActivity.ATTR_AVATAR);
                        String nickname = message.getStringAttribute(ChatActivity.ATTR_NICK);
                        User user = UserUtils.getUserInfo(userid);
                        if (user != null) {
                            System.out.println(userid + " user null");
                            boolean change = false;
                            if (!user.getNick().equals(nickname)) {
                                user.setNick(nickname);
                                change = true;
                            }
                            if (!user.getAvatar().equals(avatar)) {
                                user.setAvatar(avatar);
                                change = true;
                            }
                            if (change) {
                                UserUtils.saveUserInfo(user);
                            }
                        } else {
                            user = new User(userid);
                            user.setAvatar(avatar);
                            user.setNick(nickname);
                            UserUtils.saveUserInfo(user);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
//                        Toast.makeText(AppContext.getInstance(), "用户信息错误", Toast.LENGTH_SHORT).show();
                    }
                }

                HXSDKHelper.getInstance().getNotifier().onNewMesg(messages);
                refreshUI();
                break;
            }

            case EventConversationListChanged: {
                refreshUI();
                break;
            }

            default:
                break;
        }
    }

    /**
     *
     */
    private void refreshUI() {
        runOnUiThread(new Runnable() {
            public void run() {
                // 刷新bottom bar消息未读数
                updateUnreadLabel();
                // 当前页面如果为聊天历史页面，刷新此页面
                if (mainPartner != null) {
                    mainPartner.refreshMessage();
                }
            }
        });
    }


    /**
     * 刷新未读消息数
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
//        if (count > 0) {
//            unreadLabel.setText(String.valueOf(count));
//            unreadLabel.setVisibility(View.VISIBLE);
//        } else {
//            unreadLabel.setVisibility(View.INVISIBLE);
//        }
    }


    /**
     * 刷新申请与通知消息数
     */
    public void updateUnreadAddressLable() {
        runOnUiThread(new Runnable() {
            public void run() {
//                int count = getUnreadAddressCountTotal();
//                if (count > 0) {
////					unreadAddressLable.setText(String.valueOf(count));
//                    unreadAddressLable.setVisibility(View.VISIBLE);
//                } else {
//                    unreadAddressLable.setVisibility(View.INVISIBLE);
//                }
            }
        });

    }

    /**
     * 获取未读申请与通知消息
     *
     * @return
     */
    public int getUnreadAddressCountTotal() {
        int unreadAddressCountTotal = 0;
        if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList().get(Constant.NEW_FRIENDS_USERNAME) != null)
            unreadAddressCountTotal = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList().get(Constant.NEW_FRIENDS_USERNAME)
                    .getUnreadMsgCount();
        return unreadAddressCountTotal;
    }

    /**
     * 获取未读消息数
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
        for (EMConversation conversation : EMChatManager.getInstance().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }

//    /***
//     * 好友变化listener
//     */
//    public class MyContactListener implements EMContactListener {
//
//        @Override
//        public void onContactAdded(List<String> usernameList) {
//            System.out.println("添加了");
//            // 保存增加的联系人
//            Map<String, User> localUsers = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList();
//            Map<String, User> toAddUsers = new HashMap<String, User>();
//            for (String username : usernameList) {
//                User user = setUserHead(username);
//                // 添加好友时可能会回调added方法两次
//                if (!localUsers.containsKey(username)) {
//                    userDao.saveContact(user);
//                }
//                toAddUsers.put(username, user);
//            }
//            localUsers.putAll(toAddUsers);
////            // 刷新ui
//            mainPartner.friendsRefresh();
//
//        }
//
//        @Override
//        public void onContactDeleted(final List<String> usernameList) {
//            // 被删除
//            System.out.println("删除了");
//            Map<String, User> localUsers = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList();
//            for (String username : usernameList) {
//                localUsers.remove(username);
//                userDao.deleteContact(username);
//                inviteMessgeDao.deleteMessage(username);
//            }
//            runOnUiThread(new Runnable() {
//                public void run() {
//                    // 如果正在与此用户的聊天页面
//                    String st10 = "您被对方删除";
//                    if (ChatActivity.activityInstance != null
//                            && usernameList.contains(ChatActivity.activityInstance.getToChatUsername())) {
//                        Toast.makeText(MainActivity.this, ChatActivity.activityInstance.getToChatUsername() + st10, Toast.LENGTH_SHORT)
//                                .show();
//                        ChatActivity.activityInstance.finish();
//                    }
//                    updateUnreadLabel();
////                    // 刷新ui
//                    mainPartner.friendsRefresh();
//                    mainPartner.refreshMessage();
//                }
//            });
//        }
//
//        @Override
//        public void onContactInvited(String username, String reason) {
//            System.out.println("邀请了");
//            // 接到邀请的消息，如果不处理(同意或拒绝)，掉线后，服务器会自动再发过来，所以客户端不需要重复提醒
//            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
//
//            for (InviteMessage inviteMessage : msgs) {
//                if (inviteMessage.getGroupId() == null && inviteMessage.getFrom().equals(username)) {
//                    inviteMessgeDao.deleteMessage(username);
//                }
//            }
//            // 自己封装的javabean
//            InviteMessage msg = new InviteMessage();
//            msg.setFrom(username);
//            msg.setTime(System.currentTimeMillis());
//            msg.setReason(reason);
//            Log.d("Main", username + "请求加你为好友,reason: " + reason);
//            // 设置相应status
//            msg.setStatus(InviteMessage.InviteMesageStatus.BEINVITEED);
//            notifyNewIviteMessage(msg);
//
//        }
//
//        @Override
//        public void onContactAgreed(String username) {
//            System.out.println("同意了");
//            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
//            for (InviteMessage inviteMessage : msgs) {
//                if (inviteMessage.getFrom().equals(username)) {
//                    return;
//                }
//            }
//            // 自己封装的javabean
//            InviteMessage msg = new InviteMessage();
//            msg.setFrom(username);
//            msg.setTime(System.currentTimeMillis());
//            Log.d("Main", username + "同意了你的好友请求");
//            msg.setStatus(InviteMessage.InviteMesageStatus.BEAGREED);
//            notifyNewIviteMessage(msg);
//
//            mainPartner.friendsRefresh();
//        }
//
//        @Override
//        public void onContactRefused(String username) {
//            System.out.println("阱");
//            // 参考同意，被邀请实现此功能,demo未实现
//            Log.d(username, username + "拒绝了你的好友请求");
//
//        }
//
//    }

    /**
     * 连接监听listener
     */
    public class MyConnectionListener implements EMConnectionListener {

        @Override
        public void onConnected() {
            boolean groupSynced = HXSDKHelper.getInstance().isGroupsSyncedWithServer();
            boolean contactSynced = HXSDKHelper.getInstance().isContactsSyncedWithServer();

            // in case group and contact were already synced, we supposed to notify sdk we are ready to receive the events
            if (groupSynced && contactSynced) {
                new Thread() {
                    @Override
                    public void run() {
                        HXSDKHelper.getInstance().notifyForRecevingEvents();
                    }
                }.start();
            } else {
//                if (!groupSynced) {
//                    asyncFetchGroupsFromServer();
//                }

//                if (!contactSynced) {
//                    asyncFetchContactsFromServer();
//                }
//
//                if (!HXSDKHelper.getInstance().isBlackListSyncedWithServer()) {
////                    asyncFetchBlackListFromServer();
//                }
            }

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
//                    chatHistoryFragment.errorItem.setVisibility(View.GONE);
                }

            });
        }

        @Override
        public void onDisconnected(final int error) {
            final String st1 = "无法连接到服务器";
            final String st2 = "当前网络状况";
            System.out.println(st1 + error);
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
//                    if (error == EMError.USER_REMOVED) {
//                        // 显示帐号已经被移除
//                        showAccountRemovedDialog();
//                    } else if (error == EMError.CONNECTION_CONFLICT) {
//                        // 显示帐号在其他设备登陆dialog
//                        showConflictDialog();
//                    } else {
//                        chatHistoryFragment.errorItem.setVisibility(View.VISIBLE);
//                        if (NetUtils.hasNetwork(MainActivity.this))
//                            chatHistoryFragment.errorText.setText(st1);
//                        else
//                            chatHistoryFragment.errorText.setText(st2);
//
//                    }
                    UIHelper.ToastMessage(MainActivity.this, "应用异常");

                }

            });
            AppManager.getAppManager().finishAllActivity();
            finish();
            System.exit(0);
        }

    }

//    /**
//     * MyGroupChangeListener
//     */
//    public class MyGroupChangeListener implements EMGroupChangeListener {
//
//        @Override
//        public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) {
//
//            boolean hasGroup = false;
//            for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) {
//                if (group.getGroupId().equals(groupId)) {
//                    hasGroup = true;
//                    break;
//                }
//            }
//            if (!hasGroup)
//                return;
//
//            // 被邀请
//            String st3 = "邀请你加入群聊";
//            EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
//            msg.setChatType(EMMessage.ChatType.GroupChat);
//            msg.setFrom(inviter);
//            msg.setTo(groupId);
//            msg.setMsgId(UUID.randomUUID().toString());
//            msg.addBody(new TextMessageBody(inviter + " " + st3));
//            // 保存邀请消息
//            EMChatManager.getInstance().saveMessage(msg);
//            // 提醒新消息
//            HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg);
//
//            runOnUiThread(new Runnable() {
//                public void run() {
//                    updateUnreadLabel();
////                    // 刷新ui
//                    mainPartner.refreshMessage();
//                    mainPartner.groupRefresh();
//                }
//            });
//
//        }
//
//        @Override
//        public void onInvitationAccpted(String groupId, String inviter, String reason) {
//            mainPartner.groupRefresh();
//        }
//
//        @Override
//        public void onInvitationDeclined(final String groupId, String invitee, String reason) {
//            runOnUiThread(new Runnable() {
//                              public void run() {
//                                  UIHelper.ToastMessage(MainActivity.this, "邀请入群" + groupId + "被拒绝");
//                              }
//                          }
//
//            );
//        }
//
//        @Override
//        public void onUserRemoved(final String groupId, String groupName) {
//
//            // 提示用户被T了，demo省略此步骤
//            // 刷新ui
//            runOnUiThread(new Runnable() {
//                public void run() {
//                    try {
//                        updateUnreadLabel();
//                        mainPartner.groupRefresh();
//                        UIHelper.ToastMessage(MainActivity.this, "您已被管理员剔除群" + groupId);
//                    } catch (Exception e) {
//                        EMLog.e("Main", "refresh exception " + e.getMessage());
//                    }
//                }
//            });
//        }
//
//        @Override
//        public void onGroupDestroy(final String groupId, String groupName) {
//            // 群被解散
//            // 提示用户群被解散,demo省略
//            // 刷新ui
//            runOnUiThread(new Runnable() {
//                public void run() {
//                    updateUnreadLabel();
//                    mainPartner.groupRefresh();
//                    UIHelper.ToastMessage(MainActivity.this, "群" + groupId + "已被解散");
//                }
//            });
//
//        }
//
//        @Override
//        public void onApplicationReceived(String groupId, String groupName, String
//                applyer, String reason) {
//
//            // 用户申请加入群聊
//            InviteMessage msg = new InviteMessage();
//            msg.setFrom(applyer);
//            msg.setTime(System.currentTimeMillis());
//            msg.setGroupId(groupId);
//            msg.setGroupName(groupName);
//            msg.setReason(reason);
//            Log.d("Main", applyer + " 申请加入群聊：" + groupName);
//            msg.setStatus(InviteMessage.InviteMesageStatus.BEAPPLYED);
//            notifyNewIviteMessage(msg);
//        }
//
//        @Override
//        public void onApplicationAccept(String groupId, String groupName, String accepter) {
//
//            String st4 = "群主同意你加入";
//            // 加群申请被同意
//            EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
//            msg.setChatType(EMMessage.ChatType.GroupChat);
//            msg.setFrom(accepter);
//            msg.setTo(groupId);
//            msg.setMsgId(UUID.randomUUID().toString());
//            msg.addBody(new TextMessageBody(accepter + " " + st4));
//            // 保存同意消息
//            EMChatManager.getInstance().saveMessage(msg);
//            // 提醒新消息
//            HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg);
//
//            runOnUiThread(new Runnable() {
//                public void run() {
//                    updateUnreadLabel();
//                    // 刷新ui
//                    mainPartner.refreshMessage();
//                    mainPartner.groupRefresh();
//                }
//            });
//        }
//
//        @Override
//        public void onApplicationDeclined(final String groupId, String groupName, String
//                decliner, String reason) {
//            // 加群申请被拒绝，demo未实现
//            runOnUiThread(new Runnable() {
//                              public void run() {
//                                  UIHelper.ToastMessage(MainActivity.this, "申请入群" + groupId + "被拒绝");
//                              }
//                          }
//
//            );
//        }
//    }

//    /**
//     * 保存提示新消息
//     *
//     * @param msg
//     */
//    private void notifyNewIviteMessage(InviteMessage msg) {
//        saveInviteMsg(msg);
//        // 提示有新消息
//        HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(null);
//
//        // 刷新bottom bar消息未读数
//        updateUnreadAddressLable();
////        // 刷新好友页面ui
//        if (mainPartner != null)
//            mainPartner.friendsRefresh();
//    }
//
//    /**
//     * 保存邀请等msg
//     *
//     * @param msg
//     */
//    private void saveInviteMsg(InviteMessage msg) {
//        // 保存msg
////        inviteMessgeDao.saveMessage(msg);
//        // 未读数加1
//        User user = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList().get(Constant.NEW_FRIENDS_USERNAME);
//        if (user.getUnreadMsgCount() == 0)
//            user.setUnreadMsgCount(user.getUnreadMsgCount() + 1);
//    }


    private BroadcastReceiver avtarChangedReciver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            initUserHead();
        }
    };

}
